import { Component, OnInit,Output,Input,EventEmitter,ViewChild } from '@angular/core';
import {Service} from '../../../server/server';
import {HttpClient} from '@angular/common/http';
import * as moment from 'moment';
import {CudTableService} from '../../../public/serve/cud-table/cud-table.service';
import {RemoveTableService} from '../../../public/serve/remove-table/remove-table.service';
import {keywordTableAddtype} from '../../../system/keyword-table-management/keywordtable.data';
import {InternalIndexedModalTableComponent} from '../../internal-indexed-modal-table/internal-indexed-modal-table.component';
import {HintsService} from '../../../public/serve/hints/hints.service';
import {InitService} from '../../../public/serve/init/init.service';
import { ActivatedRoute,Params } from '@angular/router';
import {InternalIndexedModalRelthemeComponent} from '../../internal-indexed-modal-reltheme/internal-indexed-modal-reltheme.component';
import {InternalIndexedModalTableVersionComponent} from '../../internal-indexed-modal-table-version/internal-indexed-modal-table-version.component';
import { internal } from '../../internal.data';
import { isInteger, isNumber } from '@ng-bootstrap/ng-bootstrap/util/util';
declare var $:any;

@Component({
  selector: 'app-indexing-attribute',
  templateUrl: './indexing-attribute.component.html',
  styleUrls: ['./indexing-attribute.component.css']
})
export class IndexingAttributeComponent implements OnInit {

  @Input() internalParam : any;
  status:any = '0';
  templateId:any = '';
  tabVal : Array<object>;
  pimVal : Array<object>;
  attr_type:any = 'add';//默认是新增
  taskType: any;
  themeId: number = 0;
  internalThemeInternalAttributeEmit: any;

  constructor(
    private server: Service,
    public request: CudTableService,
    private tableListService: CudTableService,
    private hintsService: HintsService,
    private removeTableService: RemoveTableService,
    public initService: InitService,
    private http: HttpClient,
    private activatedRoute: ActivatedRoute,
  ) { }

  ngOnInit() {
    this.activatedRoute.queryParams.subscribe((p: Params) => {
      this.taskType = p['taskType'];
    });

    if(this.taskType == 2){
      this.internalThemeInternalAttributeEmit = this.server.internalThemeInternalAttributeEmit.subscribe((value: any) => {
        if (value) {
          this.themeId = value.themeWordsId;
          this.getAttrList();
        }
      });
    }
  }

  ngOnDestroy() {
    this.internalThemeInternalAttributeEmit ? this.internalThemeInternalAttributeEmit.unsubscribe() : '';
  }

  getAttrList(){
    this.templateId = this.internalParam.templateId;
    this.getProductIndexingMetaList();
  }

  /**
   *  产品标引属性列表查询
   */
  getProductIndexingMetaList(){
    let data = this._pimData();
    this.request.postRequest(this.server.baseUrl +"Service/IdxProduct/getProductIndexingMetaList",data).then((res:any) => {
      if (res.result_code === '0000') {
        this.pimVal = res.result;
        if(this.pimVal && this.pimVal.length > 0){
          this.attr_type = 'edit';
        }else{
          this.attr_type = 'add';
        }
        this.getMetaDataTemplateAttrList();
      }else{
        //this.hintsService.messages(res.message,res.result_code);
      }
    })
    .catch((err: any)=>{
      this.hintsService.messages("error","error");
      return;
    });
  }

  /**
   * 模板属性列表
   */
  getMetaDataTemplateAttrList(){
    let data = this._tableData();
    this.request.postRequest(this.server.baseUrl +"Service/Config/getMetaDataTemplateAttrList",data).then((res:any) => {
      if (res.result_code === '0000') {
        this.tabVal = res.result;
        if(this.tabVal && this.pimVal){
          this.tabVal = this.getAttrValue(this.tabVal,this.pimVal);
        }
      }else{
        //this.hintsService.messages(res.message,res.result_code);
      }
    })
    .catch((err: any)=>{
      this.hintsService.messages("error","error");
      return;
    });
  }

  //获取属性的值
  getAttrValue(tempVal,pimVal){
    
    let i = 0;
    for (let temp of tempVal) {
      tempVal = this._initTimeTypeName(tempVal,temp['inputType'],i);
      for (let pim of pimVal) {
          if(temp.metaId == pim.metaId){
            if(this._isTime(temp['inputType']) == 'OTHER'){
              tempVal[i]['pimId'] = pim.id;
              tempVal[i]['metaValue'] = pim.metaValue;
            }else{
              tempVal[i]['pimId'] = pim.id;
              if(pim.metaValue){
                tempVal = this._saveTimeTypeValue(tempVal,pim.metaValue,temp['inputType'],i);
              }
            }
            
          }
      }
      i++;
    }
    return tempVal;
  }

  //初始化时间类型的字段
  _initTimeTypeName(tempVal,inputType,i){
    //年
    if(inputType == "year" || inputType == "bcyear"){
      tempVal[i]['metaValueYear'] = '';
    }
    //年月
    if(inputType == "yearmonth" || inputType == "bcyearmonth"){
      tempVal[i]['metaValueYear'] = '';
      tempVal[i]['metaValueMonth'] = '';
    }
    //年月日
    if(inputType == "date" || inputType == "bcdate"){
      tempVal[i]['metaValueYear'] = '';
      tempVal[i]['metaValueMonth'] = '';
      tempVal[i]['metaValueDay'] = '';
    }
    //年月日-时分秒
    if(inputType == "datetime" || inputType == "bcdatetime"){
      tempVal[i]['metaValueYear'] = '';
      tempVal[i]['metaValueMonth'] = '';
      tempVal[i]['metaValueDay'] = '';

      tempVal[i]['metaValueTime'] = '00';
      tempVal[i]['metaValueMinute'] = '00';
      tempVal[i]['metaValueSecond'] = '00';
    }

    return tempVal;
  }

  //赋值给时间类型的字段
  _saveTimeTypeValue(tempVal,metaValue,inputType,i){
    //年
    if(inputType == "year" || inputType == "bcyear"){
      tempVal[i]['metaValueYear'] = this._isYearMakeupFour(metaValue);
    }
    //年月
    if(inputType == "yearmonth" || inputType == "bcyearmonth"){
      let val = metaValue.split('-');
      tempVal[i]['metaValueYear'] = val[0]?this._isYearMakeupFour(val[0]):'';
      tempVal[i]['metaValueMonth'] = val[1]?this._isMonthAndDayMakeup(val[1]):'';
    }
    //年月日
    if(inputType == "date" || inputType == "bcdate"){
      let val = metaValue.split('-');
      tempVal[i]['metaValueYear'] = val[0]?this._isYearMakeupFour(val[0]):'';
      tempVal[i]['metaValueMonth'] = val[1]?this._isMonthAndDayMakeup(val[1]):'';
      tempVal[i]['metaValueDay'] =  val[2]?this._isMonthAndDayMakeup(val[2]):'';
    }
    //年月日-时分秒
    if(inputType == "datetime" || inputType == "bcdatetime"){
      let arr = metaValue.split(' ');

      if(arr[0]){
        let valYMD = arr[0].split('-');
        tempVal[i]['metaValueYear'] = valYMD[0]?this._isYearMakeupFour(valYMD[0]):'';
        tempVal[i]['metaValueMonth'] = valYMD[1]?this._isMonthAndDayMakeup(valYMD[1]):'';
        tempVal[i]['metaValueDay'] = valYMD[2]?this._isMonthAndDayMakeup(valYMD[2]):'';
      }

      if(arr[1]){
        let valTMS = arr[1].split(':');
        tempVal[i]['metaValueTime'] = valTMS[0]?this._isMonthAndDayMakeup(valTMS[0]):'00';
        tempVal[i]['metaValueMinute'] = valTMS[1]?this._isMonthAndDayMakeup(valTMS[1]):'00';
        tempVal[i]['metaValueSecond'] = valTMS[2]?this._isMonthAndDayMakeup(valTMS[2]):'00';
      }
      
    }

    return tempVal;
  }

  //查询参数
  private _tableData(){
    return {
      token         : internal.retrieval.token,
      pageNo        : 1,
      pageSize      : 20,
      status        : this.status,
      templateId    : this.templateId,
    }
  }

   //查询参数
   private _pimData(){
    return {
      token         : internal.retrieval.token,
      pageNo        : 1,
      pageSize      : 20,
      productId     : this.internalParam.productId,
      taskId        : this.internalParam.taskId,
      templateId    : this.templateId,
      themeId       : this.themeId,
      queryCriteria : ''
    }
  }

  //重组时间类型的值
  _reorganizationTimeValue(info,item,inputType){
    let metaValue = '';
    let metaId = item['metaId'];
    //年
    if(inputType == "year" || inputType == "bcyear"){
      let metaYearId = metaId+'_year';
      metaValue = this._isYearMakeupFour(info[metaYearId]);
    }
    //年月
    if(inputType == "yearmonth" || inputType == "bcyearmonth"){
      let metaYearId = metaId+'_year';
      let metaMonthId = metaId+'_month';
      let yearValue = info[metaYearId];
      if(yearValue){
        yearValue = this._isYearMakeupFour(yearValue);
        if(info[metaMonthId]){
          metaValue = yearValue + '-' + this._isMonthAndDayMakeup(info[metaMonthId]);
        }else{
          metaValue = yearValue;
        }
      }
    }
    //年月日
    if(inputType == "date" || inputType == "bcdate"){
      let metaYearId = metaId+'_year';
      let metaMonthId = metaId+'_month';
      let metaDayId = metaId+'_day';
      let yearValue = info[metaYearId];

      if(yearValue){
        yearValue = this._isYearMakeupFour(yearValue);
        if(info[metaMonthId] && info[metaDayId]){
          metaValue = yearValue + '-' + this._isMonthAndDayMakeup(info[metaMonthId]) + '-' + this._isMonthAndDayMakeup(info[metaDayId]);
        }else if(info[metaMonthId] && !info[metaDayId]){
          metaValue = yearValue + '-' + this._isMonthAndDayMakeup(info[metaMonthId]);
        }else if(!info[metaMonthId] && info[metaDayId]){
          metaValue = yearValue + '-' + ' ' + '-' + this._isMonthAndDayMakeup(info[metaDayId]);
        }else{
          metaValue = yearValue;
        }
      }
      
    }
    //年月日-时分秒
    if(inputType == "datetime" || inputType == "bcdatetime"){
      let metaYearId = metaId+'_year';
      let metaMonthId = metaId+'_month';
      let metaDayId = metaId+'_day';
      let yearValue = info[metaYearId];

      if(yearValue){
        yearValue = this._isYearMakeupFour(yearValue);
        if(info[metaMonthId] && info[metaDayId]){
          metaValue = yearValue + '-' + this._isMonthAndDayMakeup(info[metaMonthId]) + '-' + this._isMonthAndDayMakeup(info[metaDayId]);
        }else if(info[metaMonthId] && !info[metaDayId]){
          metaValue = yearValue + '-' + this._isMonthAndDayMakeup(info[metaMonthId]);
        }else if(!info[metaMonthId] && info[metaDayId]){
          metaValue = yearValue + '-' + ' ' + '-' + this._isMonthAndDayMakeup(info[metaDayId]);
        }else{
          metaValue = yearValue;
        }
      }

      let metaTimeId = metaId+'_time';
      let metaMinuteId = metaId+'_minute';
      let metaSecondId = metaId+'_second';
      if(metaValue){
        metaValue = metaValue + ' ' + this._isMonthAndDayMakeup(info[metaTimeId]) + ':' + this._isMonthAndDayMakeup(info[metaMinuteId]) + ':' + this._isMonthAndDayMakeup(info[metaSecondId]);
      }
      
    }

    return metaValue;
  }

  /**
   * 新增提交
   * @param info
   */
  _onSubmit(info:any){
    if(this.tabVal.length > 0){
      let i = 0;
      for (let item of this.tabVal) {
        let metaValue = '';
        if(this._isTime(item['inputType']) == 'OTHER'){
          metaValue = info[item['metaId']];
        }else{
          metaValue = this._reorganizationTimeValue(info,item,item['inputType']);
        }
        
        let val = {
          token : internal.retrieval.token,
          createBy : this.server.getuserName(),
          checkStatus : '0',
          templateId : this.templateId,
          metaId : item['metaId'],
          metaName : item['metaName'],
          metaValue : metaValue,
          taskId : this.internalParam.taskId,
          productId : this.internalParam.productId,
          themeId : this.themeId
        };

        i++;
        if(this.attr_type == 'add'){
          this.add_submit(val,i);//新增
        }else if(this.attr_type == 'edit'){
          val['id'] = item['pimId'];
          this.edit_submit(val,i);//修改
        }
        
      }
    }
    
  }

  //新增提交数据
  add_submit(val:any,i){
    if(val){
      this.request
      .postRequest(this.server.baseUrl + "Service/IdxProduct/addProducIndexingMeta",val)
      .then(res =>{
        if(this.tabVal.length == i){
          this.getAttrList();
          this.hintsService.messages(res.message,res.result_code);
        }
        return;
      })
      .catch(err =>{
        this.hintsService.messages("error","error");
        return;
      });
    }
  }

  //编辑提交数据
  edit_submit(val:any,i){
    if(val){
      this.request
      .postRequest(this.server.baseUrl + "Service/IdxProduct/updateProductIndexingMeta",val)
      .then(res =>{
        if(this.tabVal.length == i){
          this.getAttrList();
          this.hintsService.messages(res.message,res.result_code);
        }
        return;
      })
      .catch(err =>{
        this.hintsService.messages("error","error");
        return;
      });
    }
  }

  //验证是否是时间类型
  _isTime(inputType:string){
    let typeVal = '';
    if(inputType == 'year' || inputType == 'yearmonth' || inputType == 'date' || inputType == 'datetime'){
      typeVal = 'AD';//公元
    }else if(inputType == 'bcyear' || inputType == 'bcyearmonth' || inputType == 'bcdate' || inputType == 'bcdatetime'){
      typeVal = 'BC';//公元前
    }else{
      typeVal = 'OTHER';//其他
    }
    return typeVal;
  }

  //验证年份
  _isYear(metaValueYear){
    let flag = false;
    
    if(metaValueYear){
      let mobieReg = /^[0-9]{1,4}$/;//1到4位的年份
      let result = mobieReg.test(metaValueYear);
      if(!result){
        flag = true;//不满足条件
      }
    }
    return flag;
  }

  //验证月份
  _isMonth(metaValueYear,metaValueMonth){
    let flag = false;
    if(metaValueMonth){
      if(metaValueYear == '' || metaValueMonth < 0 || metaValueMonth > 12){
        flag = true;//不满足条件
      }
    }
    return flag;
  }

  //验证日
  _isDay(metaValueYear,metaValueMonth,metaValueDay){
    let flag = false;
    if(metaValueDay){
      if(metaValueYear == '' || metaValueMonth == '' || metaValueDay < 0 || metaValueDay > 31){
        flag = true;//不满足条件
      }
    }
    return flag;
  }

  //验证时分秒
  _isTMS(t,metaValue){
    let flag = false;
    if(metaValue){
      if(t == 't' && (metaValue < 0 || metaValue > 23)){
        flag = true;//不满足条件
      }else if(t != 't' && (metaValue < 0 || metaValue > 59)){
        flag = true;//不满足条件
      }
    }
    return flag;
  }

  //验证是否可以保存
  _timeError(){
    let flag = false;
    let divFlags = $("span[class=timeSpan]");
    if(divFlags){
      divFlags.each(function(){
        if($(this).attr('data-error')){
          flag = true;
        }
      });
    }
    return flag;
  }

  //年份不够4位的前面用0补够4位
  _isYearMakeupFour(metaValueYear){
    
    if(!this._isYear(metaValueYear) && metaValueYear && metaValueYear.length < 4){
      let zero = '';
      for (let i=0; i < 4 - metaValueYear.length; i++){
        zero += '0';
      }
      metaValueYear = zero + metaValueYear;
    }
    return metaValueYear;
  }

  //月份和日期不够2位的前面用0补够2位
  _isMonthAndDayMakeup(value){
    if(value && value.length < 2){
      value = '0' + value;
    }
    return value;
  }

}
